const app = getApp();
const db = wx.cloud.database();

// 清理字符串的函数
function cleanString(str) {
  return str.trim().replace(/\s/g, '');
}

Page({
  data: {
    tagList: [
      '年龄相仿', 
      '兴趣相投', 
      '性格温和', 
      '有稳定工作', 
      '热爱运动',
      '学历相当',
      '有责任心',
      '三观一致',
      '地域相近',
      '无不良嗜好',
      '36D',
      '180cm',
      '有肌肉',
      '微胖',
      '18岁以上'
    ],
    selectedTags: [],
    tagSelectedMap: {}
  },

  onLoad() {
    if (app.userInfo?.standard) {
      // 去除多余空格并清理字符串
      this.setData({
        selectedTags: app.userInfo.standard.split(',').map(tag => cleanString(tag))
      });
    }
    this.updateTagSelectedMap();
  },

  // 更新标签选中状态映射
  updateTagSelectedMap() {
    const map = {};
    this.data.tagList.forEach(tag => {
      const cleanedTag = cleanString(tag);
      map[tag] = this.data.selectedTags.includes(cleanedTag);
    });
    this.setData({
      tagSelectedMap: map
    });
  },

  // 判断标签是否被选中的函数
  isTagSelected(item) {
    //console.log('isTagSelected 函数被调用，参数:', item);
    const cleanedItem = cleanString(item);
    //console.log('cleanedItem:', cleanedItem);
    //console.log('selectedTags:', this.data.selectedTags);
    const result = this.data.selectedTags.includes(cleanedItem);
    //console.log('isTagSelected 函数返回值:', result);
    return result;
  },

  handleTagTap(e) {
    const tag = cleanString(e.currentTarget.dataset.tag);
    const isSelected = this.data.selectedTags.includes(tag);
    console.log('当前点击的标签:', tag);
    console.log('已选中的标签:', this.data.selectedTags);
    console.log('是否已选中:', isSelected);
    // 手动调用 isTagSelected 函数
    console.log('手动调用 isTagSelected 结果:', this.isTagSelected(tag));
    this.setData({
      selectedTags: isSelected
        ? this.data.selectedTags.filter(t => t !== tag)
        : [...this.data.selectedTags, tag]
    });
    this.updateTagSelectedMap();
    // 手动触发页面重新渲染
    this.setData({});
    wx.vibrateShort();
  },

  saveStandards() {
    if (this.data.selectedTags.length === 0) {
      wx.showToast({ title: '请至少选择一项', icon: 'none' });
      return;
    }

    wx.showLoading({ title: '保存中...' });
    db.collection('users').doc(app.userInfo._id).update({
      data: { standard: this.data.selectedTags.join(',') }
    }).then(() => {
      app.userInfo.standard = this.data.selectedTags.join(',');
      wx.hideLoading();
      wx.showToast({ title: '保存成功' });
      setTimeout(() => wx.navigateBack(), 1500);
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({ title: '保存失败', icon: 'none' });
    });
  }
});    